//package com.itheima.security;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//import org.springframework.web.servlet.ModelAndView;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.HashSet;
//import java.util.Set;
//
//@Component
//public class RoleCheckInterceptor implements HandlerInterceptor {
//
//
//public static ArrayList<String> update_role = new ArrayList<>();
//
//@Autowired
//private IUser iuser;
//
//public static Set<String> users_to_update_roles = new HashSet<>();
//
//@Override
//public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
//        throws Exception {
//
//    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//
//    try {
//
//        CurrentUser current = (CurrentUser) auth.getPrincipal();
//
//        String username = current.getUser().getUsername();
//        if (users_to_update_roles.contains(username)) {
//            updateRoles(auth, current);
//            users_to_update_roles.remove(username);
//        }
//
//    } catch (Exception e) {
//
//    }
//
//    return true;
//}
//
//@Override
//public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
//        ModelAndView modelAndView) throws Exception {
//
//}
//
//@Override
//public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
//        throws Exception {
//
//}
//
//private void updateRoles(Authentication auth, CurrentUser current) {
//    User findOne = iuser.findOne(current.getUser().getUsername());
//    List<GrantedAuthority> updatedAuthorities = new ArrayList<>();
//    for (Role role : findOne.getRoles()) {
//        updatedAuthorities.add(new SimpleGrantedAuthority(role.name()));
//    }
//
//    Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(),
//            updatedAuthorities);
//
//    SecurityContextHolder.getContext().setAuthentication(newAuth);
//}
//}